# -*- coding: utf-8 -*-
# @Time   : 2023/9/14 15:56
# @Author : 大龙 🚀
# @File   : xinjiang_illegal.py
import json
import math
import re

from apps.tax_illegal.tax_illegal.items import NetTaxIllegalProItem
from apps.tax_illegal.tax_illegal.spiders import BaseTaxIllegalSpider


class XinjiangIllegalSpider(BaseTaxIllegalSpider):
    name = "xinjiang_illegal"
    province: str = "新疆省"
    url: str = "https://etax.xinjiang.chinatax.gov.cn/yhs-web/cxzx/index.html?id=191&code=zdsswfajgg#/zdsswfajgg"

    def start_requests(self):
        yield from self.etax_search(**{"etax_url": "https://etax.xinjiang.chinatax.gov.cn:8443"})
        url = "https://etax.xinjiang.chinatax.gov.cn/zdsswfaj/query/mx"
        data = {
            "pageIndex": 0,
            "pageSize": 10,
            "data": {
                "nsrmc": "",
                "nsrsbh": "",
                "zcdz": "",
                "zzjgdm": "",
                "frxm": "",
                "frzjhm": "",
                "cwfzrxm": "",
                "cwfzrzjhm": "",
            },
        }
        yield self.FormRequest(
            url,
            body=json.dumps(data),
            headers={
                "Content-Type": "application/json;charset=UTF-8",
            },
            callback=self.parse_list,
            method="POST",
        )

    def parse_list(self, response, **kwargs):
        url = "https://etax.xinjiang.chinatax.gov.cn/zdsswfaj/query/mx"
        yield from self.parse(response, **kwargs)  # 第一页解析
        total = response.json()["total"]  # 翻页
        if total and total > 10:
            pages = math.ceil(int(total) / 10)
            for page in range(1, int(pages) + 1):
                data = {
                    "pageIndex": page,
                    "pageSize": 10,
                    "data": {
                        "nsrmc": "",
                        "nsrsbh": "",
                        "zcdz": "",
                        "zzjgdm": "",
                        "frxm": "",
                        "frzjhm": "",
                        "cwfzrxm": "",
                        "cwfzrzjhm": "",
                    },
                }
                yield self.FormRequest(
                    url,
                    body=json.dumps(data),
                    headers={
                        "Content-Type": "application/json;charset=UTF-8",
                    },
                    callback=self.parse,
                    method="POST",
                )

    def parse(self, response, **kwargs):
        info_list = response.json()["list"]
        for info in info_list:
            item = NetTaxIllegalProItem()
            item.province = self.province
            item.year = info["gsny"] + "01"

            mapping_dict = {
                "company_name": "nsrmc",
                "address": "zcdz",
                "taxpayer_id": "nsrsbh",
                # "org_code": "zzjgdm",
                "illegal_status": "ajxz",
            }
            for map_ in mapping_dict:
                setattr(item, map_, info.get(mapping_dict[map_]))
            item.city, item.country = item.resolve_register_address(info["zcdz"])
            item.legal_representative = "，".join(
                [info.get("frxm", "") or "", info.get("frxb", "") or "", info.get("frzjhm", "") or ""]
            )
            item.resp_financial = "，".join(
                [
                    info.get("cwxm", "") or "",
                    info.get("cwxb", "") or "",
                    info.get("cwzjlx", "") or "",
                    info.get("cwzjhm", "") or "",
                ]
            ) if info.get("cwzjhm") else ""
            item.illegal_legal_representative = "，".join(
                [info.get("wffrxm", "") or "", info.get("wffrxb", "") or "", info.get("wffrzjhm", "") or ""]
            )
            illegal_facts_src = info["wfss"]
            illegal_facts = re.findall(
                r"(.*(?:主要存在|存在以下问题)(?:[^根]*?[。，;；])*)[^。]*?(?:根据|依照|依据)+", illegal_facts_src
            )
            illegal_facts = illegal_facts[0].replace('"', "") if illegal_facts else ""
            if illegal_facts:
                basis_and_punishment = illegal_facts_src.replace(illegal_facts, "").replace("\n", "").replace('"', "")
            else:
                illegal_facts = illegal_facts_src
                basis_and_punishment = ""
            item.basis_and_punishment = basis_and_punishment
            item.illegal_facts = illegal_facts

            yield item


if __name__ == "__main__":

    from scrapy import cmdline

    cmdline.execute(argv=["scrapy", "crawl", "xinjiang_illegal"])
